在Ruby中,迴圈可以分成好幾種 :
1. for-in 迴圈
2. 迭代式迴圈 (iteration)
3. while 迴圈
4. loop 迴圈
5. method 式迴圈 (ruby 特有)
前兩個比較常用,另外一般在別的語言(例如常使用到的for迴圈),在ruby是沒有這樣的寫法的
for(let i = 0; i < 10 ; i++){
console.log(i);
}
// ruby 沒有這種寫法的迴圈
names = ["eddie", "joanne", "john", "sherly"]
for name in names do
puts name
end
# eddie
# joanne
# john
# sherly
第二行的for name in names
就是在宣告變數, 宣告names裡面的東西是name
for x in 0..7 do
compilation = [1,2,1,2,1,2,4,1]
serial = '24536806'
puts serial[x].to_i * compilation[x]
end
比起使用for迴圈, 在ruby中更常用each來作迴圈
each 迴圈
names = ["eddie", "joanne", "john", "sherly"]
names.each do |name| puts name
end
如果想要印出索引值的話,可以把 |name| 改成 |name, x|
names = ["eddie", "joanne", "john", "sherly"]
names.each.with_index do |name, x|
puts "#{x} #{name}"
end
times 迴圈
3.times do
print('a')
end
# aaa
x= 0;
while x<5;
puts "hi, #{x}";
x += 1;
end
# hi, 0
# hi, 1
# hi, 2
# hi, 3
# hi, 4
x=0
until x >= 10
puts x
x += 1
end
i=0
loop do
puts i
i += 1
break if i > 10
end
# 正向從 1 數到 10
1.upto(10) do |i|
puts "hello, ruby #{i}"
end
# 反向從 10 數到 1
10.downto(1) do |i|
puts "hello, ruby #{i}"
end
# 指定迴圈要跑幾次
5.times do.
puts "hello, ruby"
end
一樣到了最後在做個練習吧,用ruby的迴圈做出一個正三角形
star = "*"
for i in 1..5 do
space = ""
k = 5-i
space = space + " "*k
print space
puts star
star += "**"
end
# *
# ***
# *****
# *******
#*********
參考資料:
https://medium.com/鳥-crl/ruby-學習筆記-04-流程控制-迴圈-loops-7a63e87df1c5
https://pjchender.dev/ruby-on-rails/ruby-loop-and-iterator/